package cn.yuanqiao.es.service.impl;

import cn.yuanqiao.es.config.ESClientPool;
import cn.yuanqiao.es.service.ElasticsearchIndex;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.CompletionProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.IndexSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: esdemo
 * @description: 索引结构基础方法实现类
 * @author: X-Pacific zhang
 * @create: 2019-01-29 10:05
 **/
@Slf4j
@Component
@Service
public class ElasticsearchIndexImpl implements ElasticsearchIndex {

    @Value(value = "${YQ_PY_SEARCH}")
    private boolean pinyin;


    /**
     * 单独新建索引名称
     *
     * @throws Exception //索引的刷新时间间隔,索引更新多久才对搜索可见(即数据写入es到可以搜索到的时间间隔，设置越小越靠近实时，但是索引的速度会明显下降，),
     *                   // 默认为1秒，如果我们对实时搜索没有太大的要求，反而更注重索引的速度，那么我们就应该设置的稍微大一些，这里设置30s
     */
    @Override
    public boolean createIndex(String indexName) {
        //构建索引类型
        IndexSettings indexSettings = new IndexSettings.Builder()
                //设置分片数,主分片数量一旦设置后就不能修改了
                .numberOfShards(String.valueOf(1))
                //每个主分片拥有的副本数,副本数量可以修改
                .numberOfReplicas(String.valueOf(0))
                //一次最多获取多少条记录
                .maxResultWindow(1000000)
                //.translog(t -> t.durability(TranslogDurability.Async))
                .build();
        if (pinyin) {
            return createIndexPY(indexName);
        }
        ElasticsearchClient client = null;
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                    .index(indexName.toLowerCase())
                    .settings(indexSettings)
                    .build();
            //执行创建索引操作并返回结果

            client = ESClientPool.getClient();
            client.indices().create(createIndexRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ESClientPool.returnClient(client);
        }
        return true;
    }

    /**
     * 创建结巴
     *
     * @param indexName
     * @return
     */
    private boolean createIndexJieba(String indexName) {
        //构建索引类型
        //构建索引类型
        IndexSettings indexSettings = new IndexSettings.Builder()
                //设置分片数,主分片数量一旦设置后就不能修改了
                .numberOfShards(String.valueOf(1))
                //每个主分片拥有的副本数,副本数量可以修改
                .numberOfReplicas(String.valueOf(0))
                //一次最多获取多少条记录
                .maxResultWindow(1000000)
                .analysis(a -> a.analyzer("jieba_search", ca -> ca.custom(cu -> cu.tokenizer("jieba_search"))))
                //.translog(t -> t.durability(TranslogDurability.Async))
                .build();
        Map<String, Property> documentMap = new HashMap<>();
        documentMap.put("TITLE", Property.of(property ->
                property.completion(CompletionProperty.of(textProperty ->
                        textProperty.analyzer("jieba_search")
                                .searchAnalyzer("jieba_search")
                                .preserveSeparators(true)
                                .maxInputLength(500)
                                .preservePositionIncrements(true))//这里设置分词
                )));
        ElasticsearchClient client = null;
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                    .index(indexName.toLowerCase())
                    .settings(indexSettings)
                    .mappings(m -> m.properties(documentMap))
                    .build();
            //执行创建索引操作并返回结果
            client = ESClientPool.getClient();
            client.indices().create(createIndexRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ESClientPool.returnClient(client);
        }
        return true;
    }


    /**
     * 创建拼音检索
     *
     * @param indexName
     * @return
     */
    private boolean createIndexPY(String indexName) {
        //构建索引类型
        //构建索引类型
        IndexSettings indexSettings = new IndexSettings.Builder()
                //设置分片数,主分片数量一旦设置后就不能修改了
                .numberOfShards(String.valueOf(1))
                //每个主分片拥有的副本数,副本数量可以修改
                .numberOfReplicas(String.valueOf(0))
                //一次最多获取多少条记录
                .maxResultWindow(1000000)
                .analysis(a -> a.analyzer("analysis-pinyin", ca -> ca.custom(cu -> cu.tokenizer("pinyin"))))
                //.translog(t -> t.durability(TranslogDurability.Async))
                .build();
        Map<String, Property> documentMap = new HashMap<>();
        documentMap.put("pathDocName", Property.of(property ->
                property.text(TextProperty.of(textProperty ->
                        textProperty.index(true).analyzer("analysis-pinyin"))//这里设置分词
                )));
        documentMap.put("pathDocText", Property.of(property ->
                property.text(TextProperty.of(textProperty ->
                        textProperty.index(true).analyzer("analysis-pinyin"))//这里设置分词
                )));
        documentMap.put("pinyin_basis_data", Property.of(property ->
                property.text(TextProperty.of(textProperty ->
                        textProperty.index(true).analyzer("analysis-pinyin"))//这里设置分词
                )));
        ElasticsearchClient client = null;
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                    .index(indexName.toLowerCase())
                    .settings(indexSettings)
                    .mappings(m -> m.properties(documentMap))
                    .build();
            //执行创建索引操作并返回结果
            client = ESClientPool.getClient();
            client.indices().create(createIndexRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ESClientPool.returnClient(client);
        }
        return true;
    }

    /**
     * 批量保存索引数据数据
     *
     * @param
     * @return boolean
     * @author hbWang
     * @date 2023/6/11 11:38
     */
    @Override
    public boolean insertDocList(List<Map<String, Object>> maps, String indexName) {
//        //判断索引是否存在
//        boolean exists = existsIndex(indexName.toLowerCase());
//        if (!exists) {
//            //不存在就新建
//            createIndex(indexName.toLowerCase());
//        }
        BulkResponse index = null;
        ElasticsearchClient client = null;
        try {
            List<BulkOperation> bulkOperations = new ArrayList<>();
            maps.forEach(a -> {
                bulkOperations.add(new BulkOperation.Builder().create(c -> c.index(indexName.toLowerCase())
                        .id(String.valueOf(a.get("ID"))).document(a)).build());
            });
            client = ESClientPool.getClient();
            log.info("共" + maps.size() + "条数据开始创建索引;");
            index = client.bulk(c -> c.index(indexName.toLowerCase()).operations(bulkOperations));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建索引失败信息:" + e.getMessage() + ";es返回信息:{}data信息:{}", index, maps);
        } finally {
            ESClientPool.returnClient(client);
            if (index.errors()) {
                log.error(";es返回信息:{}" + index);
                return false;
            }
        }
        log.info("创建索引成功 !");
        return true;
    }

    /**
     * 单条
     *
     * @param
     * @return boolean
     * @author hbWang
     * @date 2023/6/11 11:38
     */
    @Override
    public boolean insertDoc(Map<String, Object> map, String indexName) {
        IndexResponse index = null;
        ElasticsearchClient client = null;
        try {
            client = ESClientPool.getClient();
            client.index(x -> x
                    .index(indexName.toLowerCase())
                    .id(String.valueOf(map.get("ID")))
                    .document(map));

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ESClientPool.returnClient(client);
        }
        return true;
    }

    /**
     * bluk批量更新数据
     *
     * @param indexName
     * @param idList
     * @param objList
     * @return List<BulkResponseItem> items
     * @throws Exception
     */
    public List<BulkResponseItem> bulkUpdate(String indexName, List<String> idList, List<Object> objList) {
        //创建BulkOperation列表准备批量插入doc
        List<BulkOperation> bulkOperations = new ArrayList<>();
        List<BulkResponseItem> items = new ArrayList<>();
        //将id作为es id，也可不指定id es会自动生成id
        for (int i = 0; i < objList.size(); i++) {
            int finalI = i;
            //TODO 没测试不知对不对
            bulkOperations.add(BulkOperation.of(b -> b
                    .update(u -> u
                            .index(indexName.toLowerCase())
                            .id(idList.get(finalI))
                            .action(a -> a
                                    .doc(objList.get(finalI))
                            ))
            ));
        }
        ElasticsearchClient client = null;
        try {
            client = ESClientPool.getClient();
            BulkResponse bulk = client
                    .bulk(x -> x
                            .index(indexName.toLowerCase())
                            .operations(bulkOperations));
            items = bulk.items();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ESClientPool.returnClient(client);
        }
        return items;
    }


    @Override
    public boolean dropIndex(String indexName) {
        ElasticsearchClient client = null;
        try {
            client = ESClientPool.getClient();
            boolean exists = existsIndex(indexName.toLowerCase());
            if (!exists) {
                //不存在就结束
                return true;
            }
            client.indices().delete(index -> index.index(indexName.toLowerCase()));
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            ESClientPool.returnClient(client);
        }
        return false;
    }

    @Override
    public boolean dropDoc(List<String> ids, String indexName) {
        boolean exists = existsIndex(indexName.toLowerCase());
        if (!exists) {
            //不存在就结束
            return false;
        }
        // 构建批量操作对象BulkOperation的集合
        List<BulkOperation> bulkOperations = new ArrayList<>();
        // 向集合中添加需要删除的文档id信息
        ids.forEach(id -> {
            bulkOperations.add(BulkOperation.of(b -> b
                    .delete((d -> d
                            .index(indexName.toLowerCase())
                            .id(id)
                    ))
            ));
        });
        ElasticsearchClient client = null;
        try {
            client = ESClientPool.getClient();
            // 调用客户端的bulk方法，并获取批量操作响应结果
            BulkResponse response = client
                    .bulk(e -> e
                            .index(indexName.toLowerCase())
                            .operations(bulkOperations));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ESClientPool.returnClient(client);
        }
        return true;
    }


    //检验索引是否存在
    @Override
    public boolean existsIndex(String indexName) {
        ElasticsearchClient client = null;
        boolean value = false;
        try {
            client = ESClientPool.getClient();
            value = client.indices().exists(e -> e.index(indexName.toLowerCase())).value();
            //      client.cluster();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ESClientPool.returnClient(client);
        }
        return value;

    }


}
